import React, { useCallback, useEffect } from 'react';
import { outlineInfo } from '@ide/types/ideServer';
import useAppStore from '@ide/store';
import { useIdeStore } from 'ide-plugin';
import { outputWs } from '@/api';
import { addMessageListener } from '@ide/utils/extension';
// import { useAppOpenEditor } from '@/hooks/useAppOpenEditor';

const severityMap:any = {
  0: 'info',
  1: 'warning',
  2: 'error',
};
const severityLevel:any = {
  0: '低',
  1: '中',
  2: '高',
};
let fileWsListener:any;
export default function IDEOutputs({ style }: {
  style?: React.CSSProperties;
}) {
  const { outputText, setOutputText, setOriginOutputText, setFileLints, fileLints, setBottomCurrentTab } = useAppStore();
  const { updateAllEditor, currentFileTab, updateEditor, openEditor } = useIdeStore();
  // const { appOpenEditor } = useAppOpenEditor();

  const getOutput = useCallback((info: outlineInfo) => {
    const data = JSON.parse(info?.data);
    switch (data.cmd) {
      case 'build':
        if (data.lints) {
          // console.log(data)
          const linemap: any = {};
          data.lints.forEach((item: any) => {
            if (!linemap[item.file]) {
              linemap[item.file] = [];
            }
            linemap[item.file].push({
              ...item,
              lineNo: item.lineNo+1
            });
          });
          setFileLints(linemap);
          // for (const path in linemap) {
          //   updateEditor(path, {
          //     lints: linemap[path]
          //   })
          // }
        } else {
          updateAllEditor({
            lints: undefined
          });
        }
        // if (/成功<\/span>\n/.test(data.output) && currentFileTab?.path) {
        //   updateEditor(currentFileTab.path, {
        //     action: {
        //       type: 'updateOutLine'
        //     }
        //   });
        // }
        break;
      case 'end-audit': {
        const result = data?.data?.result;
        if (result) {
          const linemap: any = {};
          result.forEach((item: any) => {
            if (!linemap[item.filePath]) {
              linemap[item.filePath] = [];
            }
            const line = item.line.split('-')[0];
            const col = item.col.split('-')[0];
            const fileName = item.filePath.match(/[^/]+$/)[0];
            linemap[item.filePath].push({
              lineNo: Number(line),
              file: item.filePath,
              fromCol: Number(col) - 1,
              toCol: item.col.split('-')[1] || undefined,
              severity: 'warning',
              msg: item.details
            });
            const link = item.cweUrl ? `, <a target='_blank' href='${item.cweUrl}'>${item.cweUrl}</a>` : '';
            const output = `<span class='${severityMap[item.severity]}'>
              <span class='path' data-path='${item.filePath}' data-line='${line}' data-column='${col}'>${fileName}:${line}:${col}: </span>漏洞等级:${severityLevel[item.severity]}, 漏洞描述:${item.details}
              ${link} 
            </span>`;
            // setOutputText(output);
            setOriginOutputText(output);
          });
          setFileLints(linemap);
        }
        break;
      }
      default:
        break;
    }
    if (data.output !== 'Ouput initialized') {
      // setOutputText(data.output);
      setOriginOutputText(data.output);
    }
  }, []);
  useEffect(() => {
    fileWsListener = outputWs({});
    fileWsListener.addEventListener('message', getOutput);
    return () => {
      fileWsListener?.close();
    };
  }, [getOutput]);
  const click = useCallback((e: any) => {
    const dom: HTMLElement = e.target as HTMLElement;
    if (dom && dom.className === 'path') {
      const { path, line, column } = dom.dataset;
      if (path && line && column) {
        openEditor({
          path,
          name: path.match(/[^/]+$/)?.[0],
          action: {
            Line: Number(line),
            Ch: Number(column),
            type: 'cursor'
          }
        });
      }
    }
  }, []);
  useEffect(() => {
    if (outputText.length > 0) {
      setBottomCurrentTab('output');
    }
  }, [outputText]);
  useEffect(() => {
    if (!currentFileTab?.path) {
      return;
    }
    updateEditor(currentFileTab.path, {
      lints: fileLints[currentFileTab.path]
    });
  }, [currentFileTab, fileLints]);
  useEffect(() => {
    addMessageListener(setOutputText);
  }, []);

  return (
    <div className='output ideoutput' style={style}>
      {
        outputText.map((text, idx) => (
          <p key={idx} onClick={(e) => click(e)} dangerouslySetInnerHTML={{ __html: text }}></p>
        ))
      }
    </div>
  );
}
